package club.zhcs.module;

import java.util.List;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.lang.Lang;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.kerbores.nutz.module.base.AbstractBaseModule;
import com.kerbores.qiniu.QiNiuUploader;
import com.kerbores.utils.entries.Result;

/**
 * 
 * @author 王贵源
 *
 * @email kerbores@kerbores.com
 *
 * @description 文件上传下载
 * 
 * @copyright 内部代码,禁止转发
 *
 *
 * @time 2016年1月26日 下午3:35:25
 */
@At("file")
@Filters
public class FileModule extends AbstractBaseModule {

	@Inject
	QiNiuUploader qiNiuUploader;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kerbores.nutz.module.base.AbstractBaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return null;
	}

	/**
	 * 文件上传
	 * 
	 * @param tf
	 * @return
	 *
	 * @author 王贵源
	 */
	@SuppressWarnings("deprecation")
	@At
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	public Result upload(@Param("file") TempFile tf) {
		String key = qiNiuUploader.upload(tf.getFile());
		if (key == null) {
			return Result.fail("上传文件失败!");
		}
		return Result.success().addData("url", qiNiuUploader.privateUrl(key)).addData("key", key);
	}
	
	
	

	private List<String> allowed = Lang.array2list(new String[] { ".png", ".jpg" });// GOON

	@At
	@SuppressWarnings("deprecation")
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	public Result u(@Param("file") TempFile tf) {

		String extension = tf.getMeta().getFileExtension();

		if (!allowed.contains(extension)) {
			return Result.fail("不支持上传扩展名为 '" + extension+ "' 的文件");
		}
		String key = qiNiuUploader.upload(tf.getFile());
		if (key == null) {
			return Result.fail("上传文件失败!");
		}
		return Result.success().addData("url", qiNiuUploader.privateUrl(key)).addData("key", key);
	}
}
